<template>
    <el-card shadow="hover" :body-style="{ padding: '20px' }">
        <!-- 添加品牌的按钮 -->
        <el-button type="primary" size="default" :icon="Plus" @click="dialogFormVisible=true">添加</el-button>
        <!-- 展示商品数据的表格 -->
        <el-table border style="margin: 20px 0px;" :data="tmObj.records" v-loading="loading"
            element-loading-text="努力加载中...">
            <el-table-column label="序号" align="center" width="80" type="index"></el-table-column>
            <el-table-column label="品牌名称" align="center" prop="tmName"></el-table-column>
            <el-table-column label="品牌LOGO" align="center">
                <template #="{ row, $index }">
                    <a title="row.tmName">
                        <img :src="row.logoUrl" style="width:100px;height:80px;">
                    </a>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #="{ row, $index }">
                    <el-button type="warning" size="default" :icon="Edit" @click=updateTrademark(row)></el-button>
                    <el-popconfirm :title="`你确定删除${row.tmName}?`" width="250px" :icon="Delete" @confirm="handler(row)">
                        <template #reference>
                            <el-button type="danger" size="small" :icon="Delete"></el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页器 -->
        <el-pagination v-model:current-page="currentPage" @current-change="getTradeMarkList"
            v-model:page-size="pageSize" @size-change="sizeHandler" :page-sizes="[3,5,7]"
            layout="prev, pager, next, jumper,->,sizes,total" :total="tmObj.total" background :pager-count="7">
        </el-pagination>

        <!-- 添加弹窗 -->
        <el-dialog v-model="dialogFormVisible" :title="tmParams.id?'修改品牌':'添加品牌'" draggable @click="addTrademark">
            <el-form style="width:80%" label-width="90px" :model="tmParams" :rules="rules" ref="formRef">
                <!-- 品牌名称 -->
                <el-form-item label="品牌名称" prop="tmName">
                    <el-input autocomplete="off" v-model="tmParams.tmName" />
                </el-form-item>
                <!-- 品牌LOGO -->
                <el-form-item label="品牌LOGO" prop="logoUrl">
                    <el-upload class="avatar-uploader" action="/api/admin/product/fileUpload" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="tmParams.logoUrl" :src="tmParams.logoUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>
            <!-- 弹窗底部 -->
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogFormVisible = false">取消</el-button>
                    <el-button type="primary" @click="addOrUpdate">确认</el-button>
                </span>
            </template>
        </el-dialog>

    </el-card>
</template>

<script setup lang="ts">
//引入上传图片成功人家需要的类型
import type { UploadProps, FormInstance, FormRules } from "element-plus";
//消息提示框
import { ElMessage, ElNotification } from "element-plus";
//引入请求函数
import {
    reqTradeMarkList,
    reqAddOrUpdateTradeMark,
    reqDeleteTradeMark,
} from "../../../api/product/trademark/trademark";
//引入element-plus提供icon图标组件
import {
    Check,
    Delete,
    Edit,
    Message,
    Search,
    Star,
    Plus,
    UploadFilled,
} from "@element-plus/icons-vue";
import { ref, onMounted, reactive, nextTick } from "vue";
//引入数据类型
import type {
    trademarkResponseData,
    trademark,
} from "../../../api/product/trademark/model/trademark";
//保存分页器当前页码[当前第几页]
let currentPage = ref<number>(1);
//保存当前页面显示几条数据
let pageSize = ref<number>(3);
//定义控制loding效果响应式数据
let loading = ref<boolean>(false);
//存储组件实例el-form
let formRef = ref<FormInstance>();
//控制dialog对话框显示与隐藏
let dialogFormVisible = ref<boolean>(false);

let st = ref<boolean>(false)

//收集新增品牌数据-将来发请求携带给服务器
let tmParams = reactive<trademark>({
    tmName: "",
    logoUrl: "",
});

//定义接受服务器返回的品牌数据:total|records
let tmObj = reactive<trademarkResponseData>({
    total: 0,
    records: [],
});
//组件挂载完毕需要先获取一次品牌数据:第一页、三条数据
onMounted(() => {
    //先获取一次品牌数据
    getTradeMarkList(1);
});
//专门获取品牌数据的函数
//由于当前函数作为分页器的回调函数:人家底层会注入当前页码
const getTradeMarkList = async (page: number = 1) => {
    //发请求之前loading加载
    loading.value = true;
    //参数整理一下
    currentPage.value = page;
    //再次发请求
    let result = await reqTradeMarkList(currentPage.value, pageSize.value);
    //保存服务器返回的数据
    tmObj.total = result.total; //数据总条数
    tmObj.records = result.records; //品牌的数据
    //服务器数据回来loading效果没有
    loading.value = false;
};
//右边下拉菜单修改一页展示几条数据的回调
const sizeHandler = (limit: number) => {
    //整理参数
    pageSize.value = limit;
    //再次发请求
    getTradeMarkList();
};

//上传图片成功的钩子
const handleAvatarSuccess: UploadProps["onSuccess"] = (
    response,
    uploadFile
) => {
    //response:上传图片成功服务器返回数据
    //图片学校远程服务器地址
    tmParams.logoUrl = response.data;
};

//图片上传成功之前的钩子
const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
    //图片相关的信息
    //外层约束类型
    if (
        rawFile.type == "image/jpeg" ||
        rawFile.type == "image/png" ||
        rawFile.type == "image/gif"
    ) {
        //约束大小1024B->1K->1M->1G->1T
        if (rawFile.size / 1024 / 1024 <= 5) {
            return true;
        }
    } else {
        return false;
    }
};

//确定按钮的回调
const addOrUpdate = async () => {
    //触发el-form组件实例的validate方法
    //全部字段进行校验
    formRef.value.validate(async (success) => {
        //如果全部字段校验成功
        if (success) {
            //添加品牌或者修改品牌的请求
            await reqAddOrUpdateTradeMark(tmParams);
            //对话框关闭
            dialogFormVisible.value = false;
            //再次获取最新的全部品牌的数据
            //如果是新增品牌分页器留在第一页|如果是修改留在当前页面
            getTradeMarkList(tmParams.id ? currentPage.value : 1);
            //添加成功显示文字信息
            ElMessage({
                type: "success",
                message: tmParams.id ? "修改品牌成功" : "添加品牌成功",
            });
        } else {
            ElNotification({
                type: "warning",
                message: "大哥你看点规则,别瞎搞",
                duration: 500, //提示消息时间的设置
            });
        }
    });
};

//添加品牌按钮的回调
const addTrademark = () => {
    //对话框显示出来
    dialogFormVisible.value = true;
    //每一次对话框显示出来的时候，先清空数据[把上一次收集的数据不要了，从新收集]
    tmParams.tmName = "";
    tmParams.logoUrl = "";
    tmParams.id = "";

    //每一次点击添加按钮重置表单验证信息[上一次验证信息清空]
    // formRef.value.resetFields();

    //nextTick:当响应式数据发生变化[页面重新渲染],获取更新后的DOM
    nextTick(() => {
        formRef.value.resetFields();
    });
};

//表格第四列修改按钮回调
const updateTrademark = (row: trademark) => {
    //对话框显示
    dialogFormVisible.value = true;

    //收集修改 已有品牌 数据
    nextTick(() => {
        //重置初始化，再次重新赋值
        //重置该表单项，将其值重置为初始值，并移除校验结果
        formRef.value.resetFields();
        tmParams.id = row.id; //需要有id
        tmParams.tmName = row.tmName;
        tmParams.logoUrl = row.logoUrl;
    });
};

//自定义校验规则
const validatetmName = (rule: any, value: any, next: any) => {
    //rule:校验规则对象
    //value:内容
    //next:函数。放行函数
    //正则对象test：符合条件返回真、否则false
    ///^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\.[a-zA-Z0-9]{2,6}$/
    if (value.length > 2) {
        next();
    } else {
        next(new Error("品牌名字大于2"));
    }
};

//表单验证规则
const rules = reactive<FormRules>({
    //tmName品牌名字校验规则书写
    tmName: [
        //required:校验前面加上星星    message:触发这个规则的时候提示错误信息    trigger:触发规则实际 [失却焦点blur   当文本发生变化时候触发 change]
        //min:2,max:10 设置表单文本个数设置[最小数值与最大数值]
        // { required: true, message: "亲爱的品牌名字不能为空", trigger: "blur" },
        // {required: true,min: 2,max: 10,message: "亲爱的品牌名称2-10",trigger: "change"},
        // 自定义校验规则validator,自定义校验规则
        { required: true, trigger: "blur", validator: validatetmName },
    ],
    logoUrl: [{ required: true, message: "请你上传logo图片" }],
});

//删除某一个品牌数据
const handler = async (row: trademark) => {
    try {
        //删除品牌成功
        await reqDeleteTradeMark(row.id);
        //提示信息
        ElMessage({
            type: "success",
            message: `删除${row.tmName}成功`,
        });
        //再次获取最新数据
        getTradeMarkList(currentPage.value);
    } catch (error) { }
};
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
    
<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>